//
//  ImagePlayerController.m
//  tongXingHotel
//
//  Created by admin on 11-11-10.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//
#import "Constants.h"
#import "ProdListController.h"
//#import "JXWBuyWebViewController.h"
#import "JXWBuyNavigationController.h"
#import "UILabelStrike.h"
//#define  imageMenuLinkHeight 5
//#define  titleViewHeight 45
//#define prodlist_titleViewHeight 46


#define  adv_height_portrait 50//广告高度

#define  prodlist_cell_space 6
#define  cell_width 153
#define  cell_image_space 5
#define  price_height 30
#define  prodlist_image_width 143
#define  prodlist_left_space_portrait 0
//#define  prodlist_left_space_Landscape 22
#define  tag_base_cell 10000
#define  tag_base_reuse 100
#define  tag_base_prodname 20
#define  tag_base_prodprice 21
#define  tag_base_prodimage 22

#define  prodlist_tag_activityIndicator 10
#define  prodlist_tag_loadTip 11
#define  prodlist_tag_adv 12


@implementation ProdListController


@synthesize scrollView;
@synthesize coverpartid;
@synthesize paramsDic;
 
@synthesize isShowAdv;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
   // [MobClick beginLogPageView:@"prodList"];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
   // [MobClick endLogPageView:@"prodList"];
}

/**
 添加参数，用于获取商品的URL params
 */
-(void) addParams:(NSString*) value forKey:(NSString*) key{
    if(self.paramsDic ==nil){
        self.paramsDic=[ [NSMutableDictionary alloc] initWithCapacity:0 ];
    }
    [self.paramsDic setObject:value forKey:key];

}
#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    

    if(self.categoryName !=nil && ![self.categoryName isEqualToString:@""]){
        self.navigationItem.title=[NSString stringWithFormat:@"商品清单【%@】",self.categoryName];
    }
       self.scrollView.frame=self.view.frame;
       jxwDelegate = (JXWAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    
    
    self.view.backgroundColor=[UIColor colorWithWhite:0.95 alpha:1];
    
    

    
   // self.scrollView.frame=CGRectMake(0,adv_height_portrait,Landscape_full_width,portrait_full_width-adv_height_portrait);
    UIInterfaceOrientation t_orientation=[[UIApplication sharedApplication] statusBarOrientation ];
    
    if(t_orientation==UIInterfaceOrientationLandscapeLeft||t_orientation==UIInterfaceOrientationLandscapeRight){
        landScape=YES;
    }else{
        landScape=NO;
    }
    
    
    self.isShowAdv=@"1";
    
    if(nil!=self.paramsDic && nil!=[self.paramsDic objectForKey:@"showadv"] ){
        self.isShowAdv=[self.paramsDic objectForKey:@"showadv"];
    }
    
    
    beginDraggingY=0.0;
    nowDraggingY=0.0;
    [self setProdListImageViewFrame];
    //[self initColHeight];
    
    pageNum=1;
    loadMoreImageStartRow=0;
    isLoadMoreEnd=0;
    pageSize=30;
    
    pageNumHeightDic=[[NSMutableDictionary alloc] initWithCapacity:0];
    
    
    
    
    scrollView.showsVerticalScrollIndicator=YES; 
    scrollView.pagingEnabled=NO;
    // scrollView.scrollsToTop=NO;
    scrollView.delegate=self;
    scrollView.delaysContentTouches=YES;
    scrollView.canCancelContentTouches=NO;
    scrollView.decelerationRate=UIScrollViewDecelerationRateNormal; 
    //   scrollView.decelerationRate=0.9935;
    
    
    
 
    
    
    loadMoreTip=[[UILabel alloc] init];
    loadMoreTip.textAlignment=NSTextAlignmentCenter;
    loadMoreTip.tag=prodlist_tag_loadTip;
    loadMoreTip.text=@"";	
    loadMoreTip.font=[UIFont systemFontOfSize:16];
    loadMoreTip.backgroundColor=[UIColor clearColor];
     [scrollView addSubview:loadMoreTip];
    
    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.tag=prodlist_tag_activityIndicator;
    [activityIndicator stopAnimating];
    activityIndicator.hidden=YES;   
     [scrollView addSubview:activityIndicator];
    
    
    prodList=[[NSMutableArray alloc] initWithCapacity:100];
    
    reuseCellArray=[[NSMutableArray alloc] init];
    
    
    prodListData=[[NSMutableData alloc] init] ;//[[NSMutableData data] retain];
    
    [self doSearch:@"start"];
    
    
}

-(void)initColHeight{
    NSMutableArray *advList=[jxwDelegate getAdvList];
    if([@"1" isEqualToString:self.isShowAdv] && nil!=advList && [advList count]>0){
        colHeight1=0.0+adv_height_portrait ;
        colHeight2=0.0+adv_height_portrait  ;
       // colHeight3=0.0+adv_height_portrait;
        maxHeight=0.0+adv_height_portrait  ;
    }
    else{
        colHeight1=0 ;
        colHeight2=0 ;
       // colHeight3=-10.0;
        maxHeight=0.0;
 
    }
    
}

-(void)removeAllScrollSubView{
    
    for(UIView *subview in [scrollView subviews]){
        
        if(subview.tag!=prodlist_tag_activityIndicator && subview.tag!= prodlist_tag_loadTip && subview.tag!= prodlist_tag_adv)
        {  
            
            if([subview isKindOfClass:[UIImageView class]]){
                ((UIImageView *)subview).image=nil;
            }
            
            for(UIView *subsubview in [subview subviews]){
                if([subsubview isKindOfClass:[UIImageView class]]){
                    ((UIImageView *)subsubview).image=nil;
                }
                
                else if([subview isKindOfClass:[TilingView class]]){
                    subview.layer.contents=nil;
                }
                
                [subsubview removeFromSuperview];
            }
            
            [subview removeFromSuperview];
        }     
    }
    
    
}



//请求数据

-(void)doSearch:(NSString *)searchType{
    
    if([@"loadBegin" isEqualToString:loadTpye] || (nil!=prodListData && [prodListData length]>0)){
        return;
    }
    
    
    if(![CommonConfigUtil checkNetworkReachable]){
  
        [CommonConfigUtil showToast:kToastPositionCenter withTitle:@"无连接，请检查您的网络"]; 
        
		return ;
	}
    
    //开始加载及重新加载
    if([@"start" isEqualToString:searchType]|| [@"reloadStart" isEqualToString:searchType]){
        
        //重新加载
        if([@"reloadStart" isEqualToString:searchType]){
            [prodList removeAllObjects];//清掉所有数据
            [pageNumHeightDic removeAllObjects];
            [reuseCellArray removeAllObjects];
            //清掉所有子view
            
            [self removeAllScrollSubView];
            
            // [scrollView addSubview:loadMoreTip];
            //  [scrollView addSubview:activityIndicator];
            
            
        }
        
        
        scrollView.contentSize=CGSizeMake(scrollView.frame.size.width, scrollView.frame.size.height); 
        NSLog(@"scrollView.frame.origin.x=%f",scrollView.frame.origin.x);
        NSLog(@"scrollView.frame.origin.y=%f",scrollView.frame.origin.y);
        [scrollView scrollRectToVisible:scrollView.frame animated:NO];
        
        [self initColHeight];
        
        pageNum=1;
        loadMoreImageStartRow=0;
        
        loadTpye=@"loadBegin";
        
        if(landScape){
            activityIndicator.frame=CGRectMake( Landscape_full_width/2-100, 250, 30, 30);
        }
        else{
            activityIndicator.frame=CGRectMake( portrait_full_width/2-100, 250, 30, 30);
        }
        
        [activityIndicator startAnimating];
        activityIndicator.hidden=NO;  
        
        if(landScape){
            loadMoreTip.frame= CGRectMake(Landscape_full_width/2-50, 250.0, 100.0, 30);
        }
        else{
            loadMoreTip.frame= CGRectMake(portrait_full_width/2-50, 250.0, 100.0, 30);
        }    
        loadMoreTip.text=@"加载中...";
        
        
    }
    else if([@"more" isEqualToString:searchType]){
        
        /*
         if(isLoadMoreEnd==1){//如果没有更多数据直接返回
         return ;
         }   
         */ 
        
        activityIndicator.frame=CGRectMake(self.view.frame.size.width/2-100, floor(landScape?maxHeight_Landscape:maxHeight+10.0), 30, 30);
        loadMoreTip.frame= CGRectMake(self.view.frame.size.width/2-50, floor(landScape?maxHeight_Landscape:maxHeight+10.0), 100.0, 30);
        
        [activityIndicator startAnimating];
        activityIndicator.hidden=NO;  
        
        loadTpye=@"loadMore";
        loadMoreTip.text=@"加载中...";
        pageNum=pageNum+1;
        loadMoreImageStartRow=[prodList count];
        
    } 
    
    isLoadMoreEnd=0;
    app=[UIApplication sharedApplication];
    app.networkActivityIndicatorVisible=!app.networkActivityIndicatorVisible;
    
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateProgress:) userInfo:nil repeats:YES];	
    
    
    NSMutableString *url;
    
    
    if(nil!=self.coverpartid&&![@"" isEqualToString:self.coverpartid]){
        
        url= [[NSMutableString alloc] initWithFormat:@"%@/coversubject/list/?page=%i&limit=%i&coverid=%@&adid=%@",[CommonConfigUtil getInfServiceUrl],
              pageNum,
              pageSize,
              [CommonConfigUtil getCoverId],
              self.coverpartid
              ]; 
        
        
        
    }
    else {
        url = [[NSMutableString alloc] initWithFormat:@"%@/subject/list/?page=%i&pagesize=%i",[CommonConfigUtil getInfServiceUrl],
               pageNum,
               pageSize       
               ]; 
        
        if(nil!=self.paramsDic){
            for (NSString *key in self.paramsDic) {
                id keyvalue = [self.paramsDic objectForKey:key];
                
                if(nil!=keyvalue && [keyvalue isKindOfClass:[NSString class]] && ![@"" isEqualToString:keyvalue]){
                    [url appendFormat:@"&%@=%@",key,[keyvalue stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
                }
                else if(nil!=keyvalue && [keyvalue isKindOfClass:[NSNumber class]] ){
                    [url appendFormat:@"&%@=%i",key,[keyvalue intValue]]; 
                }
                
                
            }    
        }    
        
        
    }
    
    
    
    
    
    //stat params begin
    [url appendFormat:@"&source=%@",[CommonConfigUtil getVersionType]];
    NSString *openUDID=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
   // NSString *openUDID=[OpenUDID value];
    if(nil!=openUDID && ![@"" isEqualToString:openUDID]){
        [url appendFormat:@"&uuid=%@",openUDID]; 
    }
    
    
    NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
    if(nil!=[myDefaults objectForKey:@"userId"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userId"]]){
        [url appendFormat:@"&userid=%@", [myDefaults objectForKey:@"userId"]];
    }
    
    if(nil!=[myDefaults objectForKey:@"userNickname"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userNickname"]]){
        [url appendFormat:@"&username=%@", [[myDefaults objectForKey:@"userNickname"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[myDefaults objectForKey:@"deviceToken"]&&![@"" isEqualToString:[myDefaults objectForKey:@"deviceToken"]]){
        [url appendFormat:@"&token=%@",[[myDefaults objectForKey:@"deviceToken"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    //stat params end
    
    //NSLog(@"ur:%@",url);
    
    
    NSURLCache *shardCache=[[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
    [NSURLCache setSharedURLCache:shardCache];
    
	
    
	NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy: 
                           NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
    
    
    NSURLConnection *connection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
    // [NSURLConnection connectionWithRequest:request delegate:self];
    
    connection=nil;
    
}

//更新加载状态
- (void)updateProgress:(NSTimer*)theTimer{
	if( [@"loadEnd" isEqualToString:loadTpye]  ){
		[theTimer invalidate];
        [activityIndicator stopAnimating];
		activityIndicator.hidden=YES;
        app.networkActivityIndicatorVisible=NO; 
        if([prodList count]<=0){
            loadMoreTip.frame= CGRectMake(self.view.frame.size.width/2-50, 250.0, 100.0, 50);
            loadMoreTip.text=@"没有找到宝贝";
        }else{
            loadMoreTip.text=@"";
        }    
	}	
	
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [prodListData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
	if(data!=nil){
        [prodListData appendData:data];
        
    }		
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    [self jsonParser];
    [prodListData setLength:0];
    [self addImageToScrollView]; 
    
    
  	
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [prodListData setLength:0];
    app.networkActivityIndicatorVisible=NO; 
    [activityIndicator stopAnimating];
    activityIndicator.hidden=YES;
    loadMoreTip.text=@"";
    loadTpye=@"loadEnd";
    pageNum=pageNum-1; //如果由于其它原因（如：网络中断）造成数据没取到，需针页码减1
    [CommonConfigUtil showToast:kToastPositionCenter withTitle:@"网络异常，请重试"]; 
    
}

//解析数据
-(void)jsonParser{
    
    
    if(nil==prodListData||[prodListData length]<8 )
    {
        loadTpye=@"loadEnd";   
        return;   
    }
    
    
    //   NSString *strData = [[NSString alloc] initWithData:prodListData encoding:NSUTF8StringEncoding]; 
    // NSLog(@"strData:%@",strData);
    
    
    
    NSError *error=nil;
    //CJSONDeserializer *jsondeserializer=[[CJSONDeserializer alloc]init];
  //  NSDictionary *dictionary=[jsondeserializer deserialize:prodListData error:&error];
    
    
    NSDictionary *dictionary= [NSJSONSerialization JSONObjectWithData:prodListData options:kNilOptions error:&error];
    
    if(!error){
        
        
        NSArray *subjectArray=[dictionary objectForKey:@"subjects"];  
        for(int i=0;nil!=subjectArray&&i<[subjectArray count];i++){
            
            NSMutableDictionary *currentSubject=[[NSMutableDictionary alloc] initWithCapacity:0];
            
            /***********************图片处理 begin*************/
            NSString *prodId=[[subjectArray objectAtIndex:i] objectForKey:@"id"];//产品id
            NSString *photo=[[subjectArray objectAtIndex:i] objectForKey:@"photo"];//原图
            
            
            NSString *smallPhotoNetPath=[[NSString alloc ] initWithFormat:@"%@%@!300x999.jpg",[CommonConfigUtil getSubjectImageNetPath],photo];//小图 
            
            
            NSString *fileName=[photo stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
            
            NSString *smallPhotoLocalPath=[[NSString alloc ] initWithFormat:@"%@/prod_%@!300x999.jpg",[CommonConfigUtil getImageLocalPath],fileName];//图
            
       
            
            if(nil==smallPhotoNetPath)smallPhotoNetPath=@"";
            if(nil==smallPhotoLocalPath)smallPhotoLocalPath=@"";
           
            NSString *photoHeight=[[subjectArray objectAtIndex:i] objectForKey:@"photoHeight"];//原图高度
            NSString *photoWidth=[[subjectArray objectAtIndex:i] objectForKey:@"photoWidth"];//原图长度
            
            if(nil==photoHeight)photoHeight=@"0";
            if(nil==photoWidth)photoWidth=@"0";
            
            
            float photoHeightFloat=0.0;
            if(![@"0" isEqualToString:photoHeight]){
                photoHeightFloat=[photoHeight floatValue];//原图高度  
            }
            
            float photoWidthFloat=0.0;//原图长度
            if(![@"0" isEqualToString:photoWidth]){
                photoWidthFloat=[photoWidth floatValue];//原图高度  
            }
            float smallPhotoWidth=prodlist_image_width;
            float smallPhotoHeight=(photoHeightFloat*smallPhotoWidth)/photoWidthFloat;//在网格里显示的高度
            
            
            
            [currentSubject setObject:photo forKey:@"photo"];//原图
            
            
            [currentSubject setObject:smallPhotoNetPath forKey:@"smallPhotoNetPath"];
            [currentSubject setObject:smallPhotoLocalPath forKey:@"smallPhotoLocalPath"];
            
            
            [currentSubject setObject:photoHeight forKey:@"photoHeight"];//原图高度
            [currentSubject setObject:photoWidth forKey:@"photoWidth"];//原图长度     
            
            NSString *strSmallPhotoWidth=[[NSString alloc]  initWithFormat:@"%f",smallPhotoWidth] ;
            NSString *strSmallPhotoHeight=[[NSString alloc]  initWithFormat:@"%f",smallPhotoHeight] ;
            [currentSubject setObject:strSmallPhotoWidth forKey:@"smallPhotoWidth"];//小图长度
            [currentSubject setObject:strSmallPhotoHeight forKey:@"smallPhotoHeight"];//小图高度
       
            
            /***********************产品信息处理 begin*************/
            NSString *name=[[subjectArray objectAtIndex:i] objectForKey:@"name"];//产品名称
            NSString *description=[[subjectArray objectAtIndex:i] objectForKey:@"description"];//产品  
            // NSString *userid=[[subjectArray objectAtIndex:i] objectForKey:@"userid"];
            // NSString *price=[[subjectArray objectAtIndex:i] objectForKey:@"price"];
            NSString *feeUrl=[[subjectArray objectAtIndex:i] objectForKey:@"feeUrl"]; 
            NSString *shopId=[[subjectArray objectAtIndex:i] objectForKey:@"shopId"]; 
            
            
            NSString *promotionPrice=[[subjectArray objectAtIndex:i] objectForKey:@"promotionPrice"];//打折价
            NSString *price=[[subjectArray objectAtIndex:i] objectForKey:@"price"];//销售价
            if(nil==price || [@"" isEqualToString:price] )price=@"0";
            /*
            if(nil!=promotionPrice && ![@"" isEqualToString:promotionPrice] && [promotionPrice floatValue]>0 && [promotionPrice floatValue]<[price floatValue]){
                price=promotionPrice;
            }*/
            if(nil==price)price=@"0";
            
            NSString *percentage=[[subjectArray objectAtIndex:i] objectForKey:@"percentage"];
            if(nil==percentage) percentage=@"";
            NSString *saleCount=[[subjectArray objectAtIndex:i] objectForKey:@"salesCount"];
            if(nil==saleCount)saleCount=@"0";
            
            
            if(nil==promotionPrice)promotionPrice=@"0";
            if(nil==name)name=@"";
            if(nil==description)description=@"";
            // if(nil==userid)userid=@"";
            // if(nil==price)price=@"0";
            if(nil==feeUrl)feeUrl=@""; 
            if(nil==shopId)shopId=@""; 
            
            
            [currentSubject setObject:prodId forKey:@"id"];//产品id
            [currentSubject setObject:name forKey:@"name"];//产品名称
            [currentSubject setObject:description forKey:@"description"];//产品
            // [currentSubject setObject:userid forKey:@"userid"];
            [currentSubject setObject:price forKey:@"price"];
            [currentSubject setObject:feeUrl forKey:@"feeUrl"];
            [currentSubject setObject:shopId forKey:@"shopId"];  
            [currentSubject setObject:saleCount forKey:@"saleCount"];
            [currentSubject setObject:percentage forKey:@"percentage"];
            [currentSubject setObject:promotionPrice forKey:@"promotionPrice"];
            
            NSString *baoyou=[[subjectArray objectAtIndex:i] objectForKey:@"baoyou"];
            if(nil==baoyou)baoyou=@"0";
            [currentSubject setObject:baoyou forKey:@"baoyou"];
            
            [prodList addObject:currentSubject];
            
            
        }  
        
        //如果服务器返回没有数据，表示已经加载完毕
        if ([@"loadMore" isEqualToString:loadTpye]&&(nil==subjectArray||[subjectArray count]==0)) {
            pageNum=pageNum-1;
            isLoadMoreEnd=1;//是否已经加载所有图片 0：否 1：是，为1 是不再加载更多 
            
        }
        
    } 
    else if ([@"loadMore" isEqualToString:loadTpye]) {
        pageNum=pageNum-1; //如果由于其它原因（如：网络中断）造成数据没取到，需针页码减1
    }
    
    loadTpye=@"loadEnd";
    
}

//更新图片
- (void)updateImageToScrollView:(NSDictionary *)prodImageDic  
{   NSString *borderTag=[prodImageDic objectForKey:@"borderTag"];
    if(borderTag==nil)return; 
    
    
    NSString *smallPhotoNetPath=[prodImageDic objectForKey:@"smallPhotoNetPath"];
    NSString *smallPhotoLocalPath=[prodImageDic objectForKey:@"smallPhotoLocalPath"];
    
    /*
     NSString *downLoadImage=[prodImageDic objectForKey:@"downLoadImage"];
     if([@"0" isEqualToString: downLoadImage]){//download dealy
     [NSThread sleepForTimeInterval:2.0];
     }*/
    
    if([CommonConfigUtil existImageWithLocalPath:smallPhotoLocalPath]){
        [self performSelectorOnMainThread:@selector(setImage:) withObject:prodImageDic waitUntilDone:NO];  
    }
    else if([CommonConfigUtil writeImage:smallPhotoNetPath toImagePath:smallPhotoLocalPath]){
        [self performSelectorOnMainThread:@selector(setImage:) withObject:prodImageDic waitUntilDone:NO];
    }
    
    
} 




//设置图片
-(void)setImage:(NSDictionary *)prodImageDic  {
    // NSString *smallPhotoLocalPath=[prodImageDic objectForKey:@"smallPhotoLocalPath"];
    NSString *borderTag=[prodImageDic objectForKey:@"borderTag"];
    NSString *imageTag=[prodImageDic objectForKey:@"imageTag"];
    if(imageTag==nil)imageTag=@"-1"; 
    if(borderTag==nil)borderTag=@"-1"; 
    //  if(smallPhotoLocalPath==nil)smallPhotoLocalPath=@""; 
    
    // make a new TilingView for the new image
    
    UIView *borderView=[scrollView viewWithTag:[borderTag intValue] ];
    if(nil!=borderView){
        UIView *tilingView=[borderView viewWithTag:[imageTag intValue] ];
        if(nil!=tilingView){
            [tilingView setNeedsDisplay];
        }
    }   
    
    
}

-(void)setCellFrameValue{
    
    [self setCellFrameValueWithInit:NO];
    
}


-(void)setCellFrameValueWithInit:(BOOL)isInit{
    
    float col1startX=prodlist_left_space_portrait;
    float col2startX= prodlist_left_space_portrait+cell_width+prodlist_cell_space;   
 
    int startRow=loadMoreImageStartRow;
    if(isInit)startRow=0;
    
    for(int i=startRow;i<[prodList count];i++){
        
        
        NSString *smallPhotoHeightStr =[[prodList objectAtIndex:i] objectForKey:@"smallPhotoHeight"];
        
        NSString *prodName=[[prodList objectAtIndex:i] objectForKey:@"name"];
        if(nil==prodName){
            prodName=[[prodList objectAtIndex:i] objectForKey:@"description"];
            if(nil==prodName)prodName=@"";  
        } 
        
        
        //CGSize  prodNameSize=[prodName sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(prodlist_image_width, 1000) lineBreakMode:UILineBreakModeWordWrap];
        // NSString *prodNameHeightStr=[[NSString alloc ]initWithFormat:@"%f",floor(prodNameSize.height)];
        
         NSString *prodNameHeightStr=@"40.0";
        float smallPhotoHeight =floor([smallPhotoHeightStr floatValue]);
        float prodNameHeight =floor([prodNameHeightStr floatValue]);
        
        float colHeight=  floor(smallPhotoHeight+cell_image_space+prodNameHeight+cell_image_space+price_height);
        float colx=0.0;
        float coly=0.0;
        
        
        if(colHeight1<=colHeight2){
            colx=col1startX;
            coly=colHeight1+prodlist_cell_space;
            colHeight1=colHeight1+colHeight+prodlist_cell_space;
        }
        else if(colHeight2<colHeight1){
            colx=col2startX;
            coly=colHeight2+prodlist_cell_space;
            colHeight2=colHeight2+colHeight+prodlist_cell_space;
        }
        
 
        
        
        NSString *colxStr=[[NSString alloc ]initWithFormat:@"%f",colx]; 
        NSString *colyStr=[[NSString alloc ]initWithFormat:@"%f",coly]; 
       // NSString *colxLStr=[[NSString alloc ]initWithFormat:@"%f",colx_Landscape];
       // NSString *colyLStr=[[NSString alloc ]initWithFormat:@"%f",coly_Landscape];
        NSString *colHeightStr=[[NSString alloc ]initWithFormat:@"%f",colHeight]; 
        
        [[prodList objectAtIndex:i] setObject: colxStr forKey:@"colx"]; 
        [[prodList objectAtIndex:i] setObject: colyStr forKey:@"coly"]; 
       // [[prodList objectAtIndex:i] setObject: colxLStr forKey:@"colx_l"];
       // [[prodList objectAtIndex:i] setObject: colyLStr forKey:@"coly_l"];
        [[prodList objectAtIndex:i] setObject: colHeightStr forKey:@"colHeight"];
        [[prodList objectAtIndex:i] setObject: prodNameHeightStr forKey:@"prodNameHeight"];   
        
        
        //page set 
        
       // CGFloat  pageHeight_l = portrait_full_width-titleViewHeight;//
        
        CGFloat  pageHeight=Landscape_full_width;
        
        int pordPage= floor((coly-pageHeight)/pageHeight)+1;
       // int pordPage_l= floor((coly_Landscape-pageHeight_l)/pageHeight_l)+1;
        
        
        NSString *minPageKey=[NSString stringWithFormat:@"min_%i",pordPage];
        NSString *minRowStr=[pageNumHeightDic objectForKey:minPageKey];
        if(nil==minRowStr || i<[minPageKey intValue] ){
            [pageNumHeightDic setObject:[NSString stringWithFormat:@"%i",i] forKey:minPageKey];
        }
        
        NSString *maxPageKey=[NSString stringWithFormat:@"max_%i",pordPage];
        NSString *maxRowStr=[pageNumHeightDic objectForKey:maxPageKey];
        if(nil==maxRowStr || i>[maxRowStr intValue] ){
            [pageNumHeightDic setObject:[NSString stringWithFormat:@"%i",i] forKey:maxPageKey];
        }
        

        
        
        
    }
    
    

    
    
    if(colHeight1>=colHeight2 ){
        maxHeight= colHeight1;  
    }
    else if(colHeight2>colHeight1){
        maxHeight= colHeight2; 
    }
   
    
    
    if(colHeight1_Landscape>=colHeight2_Landscape&&colHeight1_Landscape>=colHeight3_Landscape &&colHeight1_Landscape>=colHeight4_Landscape){
        maxHeight_Landscape= colHeight1_Landscape;  
    }
    else if(colHeight2_Landscape>colHeight1_Landscape&&colHeight2_Landscape>=colHeight3_Landscape &&colHeight2_Landscape>=colHeight4_Landscape){
        maxHeight_Landscape= colHeight2_Landscape;  
    }
    else if(colHeight3_Landscape>colHeight1_Landscape&&colHeight3_Landscape>colHeight2_Landscape &&colHeight3_Landscape>=colHeight4_Landscape){
        maxHeight_Landscape= colHeight3_Landscape;  
    }
    else if(colHeight4_Landscape>colHeight1_Landscape&&colHeight4_Landscape>colHeight2_Landscape &&colHeight4_Landscape>colHeight3_Landscape){
        maxHeight_Landscape= colHeight4_Landscape;  
    }
    

    
    scrollView.contentSize=CGSizeMake(scrollView.frame.size.width, (landScape?maxHeight_Landscape:maxHeight)+210.0);
    
    CGRect frame=activityIndicator.frame;
    frame.origin.x=floor(self.view.frame.size.width/2-100);
    activityIndicator.frame= frame;
    
    frame=loadMoreTip.frame;
    frame.origin.x=floor(self.view.frame.size.width/2-50);
    loadMoreTip.frame= frame;
    
    
    
}




-(BOOL)getReUseCellForIndexRow:(NSInteger) i downLoadImage:(NSString *)downLoadImage{
    
    BOOL isReUse=NO;
    
    
    if(nil==reuseCellArray || [reuseCellArray count]<1) {
        isReUse=NO;
    } 
    else {
        
        
        //  UIButton *borderView=(UIButton*) [reuseCellArray objectAtIndex:0];
        UIButton *borderView=(UIButton*) [scrollView viewWithTag:[[reuseCellArray objectAtIndex:0] intValue]]; 
        //[borderView retain];
        [reuseCellArray removeObjectAtIndex:0]; 
        
        if(nil==borderView){
            isReUse=NO; 
        }
        else {
            
            // NSLog(@"reuseOneCellWithIndexRow :%i from tag:%i ",i,borderView.tag);
            borderView.hidden=NO;
            // [scrollView addSubview:borderView];
            
            NSString *prodPrice=[[prodList objectAtIndex:i] objectForKey:@"price"];
            float price=0.0;
            if(nil!=prodPrice&&![@"" isEqualToString:prodPrice]){
                price= [prodPrice floatValue];
            }
            NSString *prodPromotionPrice=[[prodList objectAtIndex:i] objectForKey:@"promotionPrice"];
            float promotionPrice=0.0;
            if(nil!=prodPromotionPrice&&![@"" isEqualToString:prodPromotionPrice]){
                promotionPrice= [prodPromotionPrice floatValue];
            }
            NSString *percentage=[[prodList objectAtIndex:i] objectForKey:@"percentage"];
            
            
            NSString *prodName=[[prodList objectAtIndex:i] objectForKey:@"name"];
            if(nil==prodName){
                prodName=[[prodList objectAtIndex:i] objectForKey:@"description"];
                if(nil==prodName)prodName=@"";  
            } 
            
            
            
            //NSString  *prodId = [[prodList objectAtIndex:i] objectForKey:@"id"];
            NSString *colxStr =[[prodList objectAtIndex:i] objectForKey:@"colx"];
            NSString *colyStr =[[prodList objectAtIndex:i] objectForKey:@"coly"];
            NSString *colxLStr =[[prodList objectAtIndex:i] objectForKey:@"colx_l"];
            NSString *colyLStr =[[prodList objectAtIndex:i] objectForKey:@"coly_l"];
            NSString *colHeightStr =[[prodList objectAtIndex:i] objectForKey:@"colHeight"];
            NSString *prodNameHeightStr =[[prodList objectAtIndex:i] objectForKey:@"prodNameHeight"];
            NSString *smallPhotoHeightStr =[[prodList objectAtIndex:i] objectForKey:@"smallPhotoHeight"];
            
            
            
            
            float colx=0.0;
            float coly=0.0;
            float colxL=0.0;
            float colyL=0.0;
            float colHeight=0.0;
            float prodNameHeight=0.0;
            float photoHeight=0.0;
            
            if(nil!=colxStr)colx=[colxStr floatValue];
            if(nil!=colyStr)coly=[colyStr floatValue];
            if(nil!=colxLStr)colxL=[colxLStr floatValue];
            if(nil!=colyLStr)colyL=[colyLStr floatValue];
            if(nil!=colHeightStr)colHeight=[colHeightStr floatValue];
            if(nil!=prodNameHeightStr)prodNameHeight=[prodNameHeightStr floatValue];
            if(nil!=smallPhotoHeightStr)photoHeight=[smallPhotoHeightStr floatValue];
            
            
            
            borderView.tag= tag_base_cell+i;
            
            CGRect borderViewframe=CGRectMake(landScape?colxL:colx, landScape?colyL:coly, cell_width, colHeight);
            
            borderView.frame=borderViewframe;
            
            
            
            
            CGRect frame=CGRectMake(cell_image_space, floor(cell_image_space+photoHeight+cell_image_space), prodlist_image_width, floor(prodNameHeight));
            UILabel *nameLabel=(UILabel*)[borderView viewWithTag:tag_base_prodname];
            if(nil!=nameLabel){
                nameLabel.frame=frame;
                nameLabel.text=prodName;
            }
            
            
            frame=CGRectMake(cell_image_space, floor(cell_image_space+photoHeight+cell_image_space+prodNameHeight), prodlist_image_width, price_height);
            
            UILabel *priceLabel=(UILabel*)[borderView viewWithTag:tag_base_prodprice];
            if(nil!=priceLabel){
                priceLabel.frame=frame;
                //  priceLabel.text=[NSString stringWithFormat:@"¥ %.2f",price];
                if(nil!=percentage && ![@"" isEqualToString:percentage]){
                    priceLabel.text=[NSString stringWithFormat:@"¥ %.2f ",promotionPrice];
                    //显示折扣图标
                    [self showZheKouImage:borderView price:promotionPrice ];
                    
                    //原价添加删除线
                    [self setStrikeOldPrice:priceLabel price:price];
                }
                else{
                    priceLabel.text=[NSString stringWithFormat:@"¥ %.2f",price];
                }  
            }
            
            
            
            TilingView *imageView=(TilingView*)[borderView viewWithTag:tag_base_prodimage];
            if(nil!=imageView){
                imageView.frame=CGRectMake(cell_image_space,cell_image_space, prodlist_image_width, floor(photoHeight));
                
                NSString *smallPhotoLocalPath =[[prodList objectAtIndex:i] objectForKey:@"smallPhotoLocalPath"];
                imageView.imageName=smallPhotoLocalPath;
                imageView.indexRow=i;
                if( [CommonConfigUtil existImageWithLocalPath:smallPhotoLocalPath]){
                    [imageView setNeedsDisplay];
                }
                else{
                    
                    NSString  *smallPhotoNetPath = [[prodList objectAtIndex:i] objectForKey:@"smallPhotoNetPath"];
                    if(nil==smallPhotoNetPath)smallPhotoNetPath=@"";
                    if(nil==smallPhotoLocalPath)smallPhotoLocalPath=@"";
                    NSString *borderTag=[NSString stringWithFormat:@"%i",tag_base_cell+i];
                    NSString *imageTag=[NSString stringWithFormat:@"%i",tag_base_prodimage];
                    NSDictionary *imageDic=[NSDictionary dictionaryWithObjectsAndKeys:smallPhotoLocalPath,@"smallPhotoLocalPath",smallPhotoNetPath,@"smallPhotoNetPath",borderTag,@"borderTag",imageTag,@"imageTag",downLoadImage,@"downLoadImage",smallPhotoHeightStr,@"photoHeight",nil];
                    
                    [NSThread detachNewThreadSelector:@selector(updateImageToScrollView:) toTarget:self withObject:imageDic]; 
                }     
            }
            
            
            NSString  *baoyou = [[prodList objectAtIndex:i] objectForKey:@"baoyou"];
            [self showBaoyouImage:borderView baoyou:baoyou];
            
            isReUse=YES;
        }
        
        //   [borderView release];
        
        
    }
    
    return isReUse;
    
}


-(void)addOneCellWithIndexRow:(NSInteger)i downLoadImage:(NSString *)downLoadImage{
    
    BOOL isReUse=[self getReUseCellForIndexRow: i downLoadImage:downLoadImage];
    
    // if([@"0" isEqualToString:downLoadImage]){
    //     isReUse=[self getReUseCellForIndexRow: i downLoadImage:downLoadImage];
    // }
    
    if(!isReUse){
        //  NSLog(@"addOneCellWithIndexRow :%i ",i);
        
        NSString *prodPrice=[[prodList objectAtIndex:i] objectForKey:@"price"];
        float price=0.0;
        if(nil!=prodPrice&&![@"" isEqualToString:prodPrice]){
            price= [prodPrice floatValue];
        }
        
        NSString *percentage=[[prodList objectAtIndex:i] objectForKey:@"percentage"];
        
        
        NSString *prodName=[[prodList objectAtIndex:i] objectForKey:@"name"];
        if(nil==prodName){
            prodName=[[prodList objectAtIndex:i] objectForKey:@"description"];
            if(nil==prodName)prodName=@"";  
        } 
        NSString *prodPromotionPrice=[[prodList objectAtIndex:i] objectForKey:@"promotionPrice"];
        float promotionPrice=0.0;
        if(nil!=prodPromotionPrice&&![@"" isEqualToString:prodPromotionPrice]){
            promotionPrice= [prodPromotionPrice floatValue];
        }

        
        //NSString  *prodId = [[prodList objectAtIndex:i] objectForKey:@"id"];
        NSString *colxStr =[[prodList objectAtIndex:i] objectForKey:@"colx"];
        NSString *colyStr =[[prodList objectAtIndex:i] objectForKey:@"coly"];
        NSString *colxLStr =[[prodList objectAtIndex:i] objectForKey:@"colx_l"];
        NSString *colyLStr =[[prodList objectAtIndex:i] objectForKey:@"coly_l"];
        NSString *colHeightStr =[[prodList objectAtIndex:i] objectForKey:@"colHeight"];
        NSString *prodNameHeightStr =[[prodList objectAtIndex:i] objectForKey:@"prodNameHeight"];
        NSString *smallPhotoHeightStr =[[prodList objectAtIndex:i] objectForKey:@"smallPhotoHeight"];
        float colx=0.0;
        float coly=0.0;
        float colxL=0.0;
        float colyL=0.0;
        float colHeight=0.0;
        float prodNameHeight=0.0;
        float photoHeight=0.0;
        
        if(nil!=colxStr)colx=[colxStr floatValue];
        if(nil!=colyStr)coly=[colyStr floatValue];
        if(nil!=colxLStr)colxL=[colxLStr floatValue];
        if(nil!=colyLStr)colyL=[colyLStr floatValue];
        if(nil!=colHeightStr)colHeight=[colHeightStr floatValue];
        if(nil!=prodNameHeightStr)prodNameHeight=[prodNameHeightStr floatValue];
        if(nil!=smallPhotoHeightStr)photoHeight=[smallPhotoHeightStr floatValue];
        
        
        CGRect borderViewframe=CGRectMake(landScape?colxL:colx, landScape?colyL:coly, cell_width, colHeight);
        
        UIButton *borderView=[[UIButton alloc] initWithFrame:borderViewframe];
        borderView.backgroundColor=[UIColor whiteColor];
        // borderView.layer.masksToBounds=YES;
        //borderView.layer.cornerRadius=10.0;    
        borderView.tag= tag_base_cell+i;  
      
        UITapGestureRecognizer *gestureRecognizer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageOnClickAction:) ];
        gestureRecognizer.numberOfTapsRequired=1;
        [borderView addGestureRecognizer:gestureRecognizer];
        
        [scrollView addSubview:borderView];
        
        
        
        // UILongPressGestureRecognizer
        
        
        
        
        CGRect frame=CGRectMake(cell_image_space, cell_image_space, prodlist_image_width,floor( photoHeight));

        
        
        NSString  *smallPhotoLocalPath = [[prodList objectAtIndex:i] objectForKey:@"smallPhotoLocalPath"];
        if(nil==smallPhotoLocalPath)smallPhotoLocalPath=@"";
        TilingView *imageView = [[TilingView alloc] initWithImageName:smallPhotoLocalPath size:CGSizeMake(prodlist_image_width, floor(photoHeight))];
        
        imageView.frame=frame;
        imageView.contentScaleFactor = 1.0;
        
        imageView.backgroundColor=[UIColor clearColor];
        imageView.pController=self;
        imageView.imagetype=0;
        imageView.imageCount=1;
        imageView.indexRow=i; 
        imageView.tag=tag_base_prodimage;    
        
        
        if([CommonConfigUtil existImageWithLocalPath:smallPhotoLocalPath]){
            //  [imageView setNeedsDisplay];
        }
        else{
            NSString  *smallPhotoNetPath = [[prodList objectAtIndex:i] objectForKey:@"smallPhotoNetPath"];
            if(nil==smallPhotoNetPath)smallPhotoNetPath=@"";
            NSString *borderTag=[NSString stringWithFormat:@"%i",tag_base_cell+i];
            NSString *imageTag=[NSString stringWithFormat:@"%i",tag_base_prodimage];
            NSDictionary *imageDic=[NSDictionary dictionaryWithObjectsAndKeys:smallPhotoLocalPath,@"smallPhotoLocalPath",smallPhotoNetPath,@"smallPhotoNetPath",borderTag,@"borderTag",imageTag,@"imageTag",downLoadImage,@"downLoadImage",nil];
            
            [NSThread detachNewThreadSelector:@selector(updateImageToScrollView:) toTarget:self withObject:imageDic]; 
            
        }
        
        [borderView addSubview:imageView];
        
        NSString *baoyou=[[prodList objectAtIndex:i] objectForKey:@"baoyou"];
        
        [self showBaoyouImage:borderView baoyou:baoyou];
    
        
        
        

        
        
        
        //产品名称
        
        frame=CGRectMake(cell_image_space, floor(cell_image_space+photoHeight+cell_image_space), prodlist_image_width, floor(prodNameHeight));
        UILabel *nameLabel=[[UILabel alloc] initWithFrame:frame];
        nameLabel.textAlignment=NSTextAlignmentCenter;
        nameLabel.font=[UIFont systemFontOfSize:14];
        nameLabel.numberOfLines=0;
        nameLabel.text=prodName;
        nameLabel.tag=tag_base_prodname;
        nameLabel.textColor=[UIColor darkGrayColor];
        nameLabel.backgroundColor=[UIColor whiteColor];
        
        
        //产品price
        frame=CGRectMake(cell_image_space, floor(cell_image_space+photoHeight+cell_image_space+prodNameHeight), prodlist_image_width, price_height);
        UILabel *priceLabel=[[UILabel alloc] initWithFrame:frame ];
        priceLabel.textAlignment=NSTextAlignmentLeft;
        priceLabel.font=[UIFont systemFontOfSize:14];
        priceLabel.numberOfLines=0;
        priceLabel.tag=tag_base_prodprice;
        priceLabel.textColor=[UIColor colorWithRed:1.0 green:0.46 blue:0.65 alpha:1.0];
        if(nil!=percentage && ![@"" isEqualToString:percentage]){
            priceLabel.text=[NSString stringWithFormat:@"¥ %.2f ",promotionPrice];
            //显示折扣图标
            [self showZheKouImage:borderView price:promotionPrice ];
            
            //原价添加删除线
            [self setStrikeOldPrice:priceLabel price:price];
        }
        else{
            priceLabel.text=[NSString stringWithFormat:@"¥ %.2f",price];
        }  
        //priceLabel.text=[NSString stringWithFormat:@"¥ %.2f",price];
        priceLabel.backgroundColor=[UIColor clearColor];
        
        
        // [scrollView addSubview:imageShowBut];
        //   [imageShowBut release];
        [borderView addSubview:nameLabel];
 
        [borderView addSubview:priceLabel];
 
        
    }
    
    
    
}



//增加图片
-(void)addImageToScrollView{
    
    [self setCellFrameValue];
    
    //  [self reloadSubView ];
    
    
    for(int i=loadMoreImageStartRow;i<[prodList count];i++){
        
        [self addOneCellWithIndexRow:i downLoadImage:@"1"];
        
    }
    
    

    
}



-(void)setAdvScrollViewFrame{
    
    if(nil!=self.isShowAdv && [@"1" isEqualToString:self.isShowAdv]){
        
        CGRect frame =CGRectMake(0, 0,0,0);
        
        NSMutableArray *advList=[jxwDelegate getAdvList];
        if(nil!=advList&& [advList count]>0){ 
            
            //float startx=landScape?prodlist_left_space_Landscape: prodlist_left_space_portrait;
            float startx=prodlist_left_space_portrait;
            float width=(landScape?Landscape_full_width:portrait_full_width)-startx*2;
            frame=CGRectMake(startx, 0,width,adv_height_portrait);
            
        }
        
        
        if(nil==advView){
            advView=[[AdvView alloc] initWithFrame:frame];
            advView.tag=prodlist_tag_adv;
            advView.delegate=self;
            
            [scrollView addSubview:advView];
        }    
        
        else{
            advView.frame=frame;
            [advView reloadAdvViewFrame];
        }
        
        
        
        //  NSLog(@"advView width:%f,height:%f",frame.size.width,frame.size.height);
    }     
}


-(void) setProdListImageViewFrame{
    
    [self setAdvScrollViewFrame];
    NSLog(@"scrollView.contentOffset.y=%f",scrollView.contentOffset.y);
    if(landScape && scrollView.contentOffset.y>0){
        CGFloat  pageHeight=Landscape_full_width;
        int oldPage= floor((scrollView.contentOffset.y-pageHeight)/pageHeight)+1;
        NSString *minPageKey=[NSString stringWithFormat:@"min_%i",oldPage];
        NSString *minRowStr=[pageNumHeightDic objectForKey:minPageKey];
        if(nil!=minRowStr && [minRowStr intValue]<[prodList count]){
            NSString *colyLStr =[[prodList objectAtIndex:[minRowStr intValue]] objectForKey:@"coly_l"];
            NSString *colyStr =[[prodList objectAtIndex:[minRowStr intValue]] objectForKey:@"coly"];
            
            if(nil!=colyLStr && nil!=colyStr){  
                float betwwenY = scrollView.contentOffset.y-[colyStr floatValue];
                [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, [colyLStr floatValue]+betwwenY) animated:NO ];
            }   
        }   
    }
    else if( scrollView.contentOffset.y>0){
        CGFloat  pageHeight_l = portrait_full_width;//
        int oldPage= floor((scrollView.contentOffset.y-pageHeight_l)/pageHeight_l)+1;
        NSString *minPageKey=[NSString stringWithFormat:@"min_l_%i",oldPage];
        NSString *minRowStr=[pageNumHeightDic objectForKey:minPageKey];
        
        if(nil!=minRowStr && [minRowStr intValue]<[prodList count]){
            NSString *colyStr =[[prodList objectAtIndex:[minRowStr intValue]] objectForKey:@"coly"];
            NSString *colyLStr =[[prodList objectAtIndex:[minRowStr intValue]] objectForKey:@"coly_l"];
            if(nil!=colyStr && nil!=colyLStr){  
                float betwwenY = scrollView.contentOffset.y-[colyLStr floatValue];
                
                [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, [colyStr floatValue]+betwwenY) animated:NO ];
            }   
        }  
        
        
        
    }
    
    
    
    if(nil!=prodList && [prodList count]>0){
        [self reloadSubView];  
    } 
    
    
    
    for(UIView *subview in [scrollView subviews]){
        
        
        if(subview.tag>=tag_base_cell){
            
            UIButton *borderView=(UIButton *)subview;
            if(nil!=borderView ){
                int i=borderView.tag-tag_base_cell;
                NSString *colxStr =[[prodList objectAtIndex:i] objectForKey:@"colx"];
                NSString *colyStr =[[prodList objectAtIndex:i] objectForKey:@"coly"];
                NSString *colxLStr =[[prodList objectAtIndex:i] objectForKey:@"colx_l"];
                NSString *colyLStr =[[prodList objectAtIndex:i] objectForKey:@"coly_l"];
                float colx=0.0;
                float coly=0.0;
                float colxL=0.0;
                float colyL=0.0;          
                if(nil!=colxStr)colx=[colxStr floatValue];
                if(nil!=colyStr)coly=[colyStr floatValue];
                if(nil!=colxLStr)colxL=[colxLStr floatValue];
                if(nil!=colyLStr)colyL=[colyLStr floatValue];
                
                borderView.frame=CGRectMake(landScape?colxL:colx, landScape?colyL:coly, borderView.frame.size.width, borderView.frame.size.height);
                
                
            }  
        }
    }
    
    
    
    
    scrollView.contentSize=CGSizeMake(scrollView.frame.size.width, (landScape?maxHeight_Landscape: maxHeight)+110.0);
    
    CGRect frame=activityIndicator.frame;
    frame.origin.x=floor(self.view.frame.size.width/2-100);
    activityIndicator.frame= frame;
    
    frame=loadMoreTip.frame;
    frame.origin.x=floor(self.view.frame.size.width/2-50);
    loadMoreTip.frame= frame;
    
    
}







-(void)setProdListLandScape:(BOOL)_landScape{
    landScape=_landScape;
    
}


-(void)viewOnClickWithIndexRow:(NSInteger)indexRow{
    
    
   [self gotoBuyController:indexRow];    //go to taobao buy
    
  

}
//显示商品详细页面
-(void) showWebView:(NSString*) url{
 
    UIStoryboard* storyBoard=[UIStoryboard storyboardWithName:@"JXWMain" bundle:nil];
    JXWBuyNavigationController* buyNavigationController=[storyBoard instantiateViewControllerWithIdentifier:@"JXWBuyNavigationController"];
    
    buyNavigationController.webURL=url;
    
    
    [self.jxwSegmentController presentViewController:buyNavigationController animated:YES completion:nil];
    storyBoard=nil;

}
- (void)gotoBuyController:(int)indexRow {
    if(indexRow<0 || indexRow>=[prodList count]){
        return ;
    }
    
    UIStoryboard* storyBoard=[UIStoryboard storyboardWithName:@"JXWMain" bundle:nil];
    JXWBuyNavigationController* buyNavigationController=[storyBoard instantiateViewControllerWithIdentifier:@"JXWBuyNavigationController"];
    
        buyNavigationController.webURL=[[prodList objectAtIndex:indexRow] objectForKey:@"feeUrl"];
    buyNavigationController.prodId=[[prodList objectAtIndex:indexRow] objectForKey:@"id"];
    buyNavigationController.productName=[[prodList objectAtIndex:indexRow] objectForKey:@"name"];
    buyNavigationController.shopId=nil;
    
    //[buyNavigationController setToolbarHidden:NO];
    
    [self.jxwSegmentController presentViewController:buyNavigationController animated:YES completion:nil];
    storyBoard=nil;
    //[buyNavigationController release];
    //[storyBoard release];
}


-(void)imageOnClickAction:(UITapGestureRecognizer *)sender{
    
    
    UIButton *button=(UIButton *)[sender view];
    int indexRow=button.tag-tag_base_cell;
    
    [self gotoBuyController:indexRow];
    
    //[webController release];

    
    
}



 





-(void) reloadSubViewWithArrowType:(NSString *)arrowType {
    
    
    int startNum=0;
    int endNum=0;
    int pordPage=floor((scrollView.contentOffset.y-scrollView.frame.size.height)/scrollView.frame.size.height)+1;    
    
    NSString *minLPageKey;
    NSString *maxLPageKey; 
    
    if(landScape){
        
        if([@"up" isEqualToString:arrowType]){//up
            minLPageKey=[NSString stringWithFormat:@"min_l_%i",pordPage-1];
            maxLPageKey=[NSString stringWithFormat:@"max_l_%i",pordPage];
        } 
        else if([@"down" isEqualToString:arrowType]){//down
            minLPageKey=[NSString stringWithFormat:@"min_l_%i",pordPage];
            maxLPageKey=[NSString stringWithFormat:@"max_l_%i",pordPage+1];
        }   
        else {
            minLPageKey=[NSString stringWithFormat:@"min_l_%i",pordPage-1];
            maxLPageKey=[NSString stringWithFormat:@"max_l_%i",pordPage+1];
            
        }
        
        
    }
    else{
        if([@"up" isEqualToString:arrowType]){//up
            minLPageKey=[NSString stringWithFormat:@"min_%i",pordPage-1];
            maxLPageKey=[NSString stringWithFormat:@"max_%i",pordPage];
        } 
        else if([@"down" isEqualToString:arrowType]){//down
            minLPageKey=[NSString stringWithFormat:@"min_%i",pordPage];
            maxLPageKey=[NSString stringWithFormat:@"max_%i",pordPage+1];
        }   
        else {
            minLPageKey=[NSString stringWithFormat:@"min_%i",pordPage-1];
            maxLPageKey=[NSString stringWithFormat:@"max_%i",pordPage+1];
            
        }
        
    } 
    
    NSString  *minLRowStr=[pageNumHeightDic objectForKey:minLPageKey];
    NSString *maxLRowStr=[pageNumHeightDic objectForKey:maxLPageKey];
    if(nil!=minLRowStr){
        startNum=[minLRowStr intValue];
    }
    else{
        startNum=0;
    }
    
    if( nil!=maxLRowStr){
        endNum=[maxLRowStr intValue];
    }else {
        // endNum=0;
        return;
    }    
    
    if(startNum<0) {startNum=0;}
    
    
    //  NSLog(@"currPageNum:%i,startNum:%i,endNum:%i",pordPage,startNum,endNum);
    
    
    for(int i=startNum;i<=endNum && i<[prodList count];i++){
        UIView *borderView=[scrollView viewWithTag:tag_base_cell+i];
        if(nil==borderView){
            
            
            float coly=0.0;
            float colyL=0.0;
            float colHeight=0.0;
            NSString *colyStr =[[prodList objectAtIndex:i] objectForKey:@"coly"];
            NSString *colyLStr =[[prodList objectAtIndex:i] objectForKey:@"coly_l"];
            NSString *colHeightLStr =[[prodList objectAtIndex:i] objectForKey:@"colHeight"];
            
            if(nil!=colyStr)coly=[colyStr floatValue];
            if(nil!=colyLStr)colyL=[colyLStr floatValue];
            if(nil!=colHeightLStr)colHeight=[colHeightLStr floatValue];
            float borderViewY=landScape?colyL:coly;
            float borderViewBottomY=borderViewY+colHeight+prodlist_cell_space;
            float borderViewMiddleY=borderViewY+colHeight/2;
            
            if((borderViewY>=scrollView.contentOffset.y && borderViewY<= scrollView.contentOffset.y+scrollView.frame.size.height) 
               || (borderViewBottomY>=scrollView.contentOffset.y && borderViewBottomY<= scrollView.contentOffset.y+scrollView.frame.size.height) 
               || (borderViewMiddleY>=scrollView.contentOffset.y && borderViewMiddleY<= scrollView.contentOffset.y+scrollView.frame.size.height) 
               ){ 
                // NSLog(@"addOneCellWithIndexRow:%i",i);
                [self addOneCellWithIndexRow:i downLoadImage:@"0"]; 
            }  
            
            
        }    
    }   
    
    
    
    //  NSLog(@"add after totalview:%i,  reuseCellArray:%i",[[scrollView subviews] count],[reuseCellArray count]);  
    
    
}








-(void)removeNotShowCell{
    
    if([prodList count]<30)return;
    
    NSArray *viewArray=[scrollView subviews];
    
    for(int i=0;i<[viewArray count];i++){
        
        UIView *borderView=[viewArray objectAtIndex:i];
        
        if(borderView.tag>=tag_base_cell  ){
            
            int prodListIndex= borderView.tag-tag_base_cell;
            
            if(prodListIndex>=0 && prodListIndex<[prodList count]-30){
                
                
                float coly=0.0;
                float colyL=0.0;
                float colHeight=0.0;
                NSString *colyStr =[[prodList objectAtIndex:prodListIndex] objectForKey:@"coly"];
                NSString *colyLStr =[[prodList objectAtIndex:prodListIndex] objectForKey:@"coly_l"];
                NSString *colHeightLStr =[[prodList objectAtIndex:prodListIndex] objectForKey:@"colHeight"];
                
                if(nil!=colyStr)coly=[colyStr floatValue];
                if(nil!=colyLStr)colyL=[colyLStr floatValue];
                if(nil!=colHeightLStr)colHeight=[colHeightLStr floatValue];
                float borderViewY=landScape?colyL:coly;
                float borderViewBottomY=borderViewY+colHeight+prodlist_cell_space;
                
                float borderViewMiddleY=borderViewY+colHeight/2;
                if(!((borderViewY>=scrollView.contentOffset.y && borderViewY<= scrollView.contentOffset.y+scrollView.frame.size.height) || (borderViewBottomY>=scrollView.contentOffset.y && borderViewBottomY<= scrollView.contentOffset.y+scrollView.frame.size.height)
                     || (borderViewMiddleY>=scrollView.contentOffset.y && borderViewMiddleY<= scrollView.contentOffset.y+scrollView.frame.size.height)
                     ) ) {
                    
                    
                    for(UIView *subview in [borderView subviews]){
                        
                        
                        if([subview isKindOfClass:[UIImageView class]]){
                            ((UIImageView *)subview).image=nil;
                        }
                        
                        else if([subview isKindOfClass:[TilingView class]]){
                            subview.layer.contents=nil;
                        }
                        
                        else if([subview  isKindOfClass:[UILabel class]]){
                            ((UILabel*)subview).text=@"";
                        }
                        
                        
                        
                        
                    }
                    
                   
                    borderView.tag=borderView.tag-tag_base_cell+tag_base_reuse;
                    borderView.frame=CGRectMake(0, 0, 0, 0);
                    borderView.hidden=YES;
                    //  NSLog(@"remove:%i",borderView.tag);
                    [reuseCellArray addObject:[NSString stringWithFormat:@"%i",borderView.tag]];
                    
                }
                
                
            } 
            
        } 
        
        
        
    } //end for 
    
 
}
//显示折扣图标
- (void)showZheKouImage:(UIButton *)borderView price:(float) price  {
    
    if(price>0.0){
        UIImageView* iv=[[UIImageView alloc] initWithFrame:CGRectMake(borderView.frame.size.width -30, 0, 20, 20)];
        iv.backgroundColor=[UIColor clearColor];
        iv.image=[UIImage imageNamed:@"zhe"];
        
        //UIImageView* iv=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"baoyou"]];
        
        [borderView addSubview:iv];
        
    }
    
}

//显示包邮图标
- (void)showBaoyouImage:(UIButton *)borderView baoyou:(NSString *)baoyou {
    if(baoyou !=nil && [@"1" isEqualToString:baoyou]){
        UIImageView* iv=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        iv.backgroundColor=[UIColor clearColor];
        iv.image=[UIImage imageNamed:@"baoyou"];
        
        //UIImageView* iv=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"baoyou"]];
        
        [borderView addSubview:iv];
        
    }
}
//添加带删除线的原价
- (void)setStrikeOldPrice:(UILabel *)priceLabel price:(float)price {
    UILabelStrike* lblOldPrice=[[UILabelStrike alloc] initWithFrame:CGRectMake(priceLabel.frame.size.width-60, 0 , 60, price_height)];
    lblOldPrice.isWithStrikeThrough=YES;
    
    lblOldPrice.textAlignment=NSTextAlignmentLeft;
    lblOldPrice.font=[UIFont systemFontOfSize:14];
    lblOldPrice.numberOfLines=0;
    
    lblOldPrice.textColor=[UIColor colorWithRed:169.0/255.0 green:169.0/255.0 blue:169.0/255.0 alpha:1.0];
    
    lblOldPrice.text=[NSString stringWithFormat:@"¥ %.2f ",price];
    
    [priceLabel addSubview:lblOldPrice];
}






-(void) reloadSubView{
    [self removeNotShowCell];
    [self reloadSubViewWithArrowType:@"" ];  
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollViewDrag{
    
    beginDraggingY=scrollViewDrag.contentOffset.y;
    
    
}

-(void)scrollViewDidEndDragging:(UIScrollView *)thescrollView willDecelerate:(BOOL)decelerate{
    
    
}



-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
}
//是否隐藏tabbar
- (void)switchTabBarHidden:(BOOL)option{
    
}
- (void)scrollViewDidScroll:(UIScrollView*)scrollViewDrag {	
  //  UITabBarController *parent=nil;
   // if([jxwDelegate.window.rootViewController isKindOfClass:[UITabBarController class]]){
    //    parent=(UITabBarController*)jxwDelegate.window.rootViewController;
        
   // }
    
    nowDraggingY=scrollViewDrag.contentOffset.y;
    
    if(nowDraggingY>(beginDraggingY+5)){
        //[tjDelegate hideTabBar];
        
        [self removeNotShowCell];
        [self reloadSubViewWithArrowType:@"down" ];
        
       // parent.tabBar.hidden=YES;
       // CGRect frame=self.scrollView.frame;
       // [self.scrollView setFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height -parent.tabBar.frame.size.height)];
    }
    else   if(nowDraggingY<(beginDraggingY-5)){
        //[tjDelegate showTabBar];
        [self removeNotShowCell];
        [self reloadSubViewWithArrowType:@"up" ];
        //parent.tabBar.hidden=NO;
    }
    
    
    // [self reloadSubView];
    
    
    if(isLoadMoreEnd==0&&[@ "loadEnd" isEqualToString:loadTpye]&&[prodList count]>0&&
       scrollViewDrag.contentOffset.y+scrollViewDrag.frame.size.height>=scrollViewDrag.contentSize.height-scrollViewDrag.frame.size.height){  
        
        // NSLog(@"dosearch more:%f,%f",scrollViewDrag.contentOffset.y,scrollViewDrag.contentSize.height);
        [self doSearch:@"more"];
        
    }
	
}




- (void)viewDidUnload
{
    [super viewDidUnload];
    
}



- (void)dealloc
{
 
    
    
    [self removeAllScrollSubView];
    
 
    
 
  
}
- (void) saveMobileStat:(NSDictionary *)params{
    [CommonConfigUtil saveMobileStat:params];
}
- (void)advSelectWithParams:(NSDictionary *) params{
    
    NSString *advid=[params objectForKey:@"advid" ];
    NSString *advtype=[params objectForKey:@"advtype" ];
    //  NSString *name=[params objectForKey:@"name" ];
    NSString *objectId=[params objectForKey:@"objectId" ];
    NSString *objectName=[params objectForKey:@"objectName" ];
    NSString *urlparams=[params objectForKey:@"urlparams" ];
    
    
    
    if(nil!=advid && ![@"" isEqualToString:advid]){
        
        NSDictionary *statParms =[NSDictionary dictionaryWithObjectsAndKeys:advid,@"objectid",@"ad",@"page",nil];
        [NSThread detachNewThreadSelector:@selector(saveMobileStat:) toTarget:self withObject:statParms];
    }
    
    
    NSLog(@"advtype==%@",advtype);
    //类型 0：商品详细页 1：分类列表 2：标签列表 3：店铺详细 4：品牌详细 5：专辑详细 6：场景详细 7：活动详细 8：appstore 9:url
    
    if([@"0" isEqualToString:advtype] || [advtype intValue]==0 ){
        
        
    }
    else  if([@"1" isEqualToString:advtype] || [advtype intValue]==1 ){
        
    }
    else  if([@"2" isEqualToString:advtype] || [advtype intValue]==2 ){
        
        
        
        
    }
    else  if([@"3" isEqualToString:advtype] || [advtype intValue]==3 ){
        
        
    }
    else  if([@"4" isEqualToString:advtype] || [advtype intValue]==4 ){
        
        
    }
    else  if([@"5" isEqualToString:advtype] || [advtype intValue]==5 ){
          
        [self addParams:objectId forKey:@"materialid"];
        [self doSearch:@"reloadStart"];
    }else  if([@"8" isEqualToString:advtype] || [advtype intValue]==8 ){
        
        
        NSString *appName=@"";
        if(nil!=urlparams && ![@"" isEqualToString:urlparams] ){
            NSArray *paramsArray=[urlparams componentsSeparatedByString:@"appname="];
            if(nil!=paramsArray &&  [paramsArray count]>1 ){
                appName= [paramsArray objectAtIndex:1 ];
            }
            
        }
        
        if(nil==appName)appName=@"";
        
        if(![@"" isEqualToString:appName] && [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:appName]]){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appName]];
        }
        else{
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:objectName]];
        }
        
    }
    else  if([@"9" isEqualToString:advtype] || [advtype intValue]==9 ){
        
        //start with app:
        if ([objectName hasPrefix:@"app:"]){
            //[self advAppUrlParseWithAppUrl:objectName withUrlparams:urlparams withUINavigationController:navigationController];
        }
        else if(nil!=objectId && ([@"1" isEqualToString:objectId] || [objectId intValue]==1)  ) {
            
            
            [self showWebView:objectName];
            // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:objectName]];
            
        }
        else {
             [self showWebView:objectName];
        }
    }
    

    
}
@end
